<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
      <el-form-item label="图件类型" prop="mapType">
        <el-select v-model="queryParams.mapType" placeholder="请选择图件类型" clearable>
          <el-option v-for="item in mapTypeData" :key="item.type" :label="item.typeName" :value="item.type"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图件名称" prop="mapName">
        <el-input v-model="queryParams.mapName" placeholder="请输入图件名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleUpload">
          <svg-icon class-name="upload-icon" icon-class="upload" /><span style="margin-left:10px">上传</span>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="Delete" @click="batchDelete">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="batchDownload">
          <svg-icon class-name="download-icon" icon-class="download" /><span
                        style="margin-left:10px">批量下载</span>
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="rtId">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
      <el-table-column label="图件类型" align="center" prop="type">
        <template #default="{row}">
          <el-link :underline="false" type="primary" @click="updateUpload(row)">{{ row.type }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="图件名称" align="center" prop="name" />
      <el-table-column label="图件描述" align="center" prop="mapDesc">
        <template #default="{row}">
          <el-popover placement="right" :width="400" trigger="click" v-if="row.mapDesc">
            <template #reference>
              <el-button type="text">查看</el-button>
            </template>
            <el-card shadow="never">
              <template #header>
                <div class="card-header">
                  <span>图件描述</span>
                </div>
              </template>
              <div v-html="mapDescHtml(row.mapDesc)"></div>
            </el-card>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="uploadUserName" />
      <el-table-column label="上传日期" align="center" prop="uploadTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{row}">
          <el-button type="text" @click="handleDown(row.attachId)">下载</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
      @pagination="getList" />

    <!-- 图件模板上传 -->
    <el-dialog title="图件模板上传" v-model="openFile" width="600px" append-to-body @close="close">
      <el-form ref="mapRef" :model="mapForm" :rules="mapRules" label-width="120px">
        <el-form-item label="图件类型" prop="type">
          <el-select v-model="mapForm.type" :disabled="viewFlag">
            <el-option v-for="item in mapTypeData" :key="item.type" :label="item.typeName" :value="item.type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图件上传" prop="attachId" v-if="!viewFlag">
            <FileUpload ref="fileUpload" :fileType="['ult']" v-model="fileList" :limit='1' @beforeUpload="beforeUpload" @uploadFile="uploadFile"></FileUpload>
        </el-form-item>
        <el-form-item label="图件名称" prop="name">
          <el-input v-model="mapForm.name" placeholder="请输入图件名称" />
        </el-form-item>
        <el-form-item label="图件描述" prop="mapDesc">
          <el-input v-model="mapForm.mapDesc" :autosize="{ minRows: 4 }" maxlength="100" show-word-limit type="textarea" placeholder="请输入图件描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="close">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="templateModule">
import { getMapType, getPage, delList, uploadSave, getView, updateSave } from '@/api/resultsReportImg/templateModule.js'

const data = reactive({
  queryParams: {
    mapType: '',
    mapName: '',
    page: 1,
    rows: 10
  },
  total: 0,
  mapTypeData: [],
  dataList: [],
  mapForm: {},
  fileList: []
})
const { queryParams, total, mapTypeData, dataList, mapForm, fileList } = toRefs(data)
const showSearch = ref(true)
const openFile = ref(false)
const loading = ref(false)
const mapRules = reactive({
  type: [{ required: true, message: '请选择图件类型！', trigger: 'change' }],
  attachId: [{ required: true, message: '请上传图件！', trigger: 'blur' }],
  name: [{ required: true, message: '请填写图件名称！', trigger: 'blur' }]
})
const {proxy} = getCurrentInstance()
const mapDescHtml = (mapDesc) => {
  return mapDesc ? mapDesc.split('').map(item => item =='\n'?'<br>':item).join('') : mapDesc
}

const getList = () => {
  getPage(queryParams.value).then(res => {
    const {code, data} = res
    if(code == 200) {
      dataList.value = data.list
      total.value = data.total
    }
  })
}
// 查询
const handleQuery = () => {
  getList()
}
// 重置
const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.value.page = 1
  handleQuery();
}
// 上传
const handleUpload = () => {
  openFile.value = true
}
// 批量删除
const batchDelete = () => {
  if(ids.length == 0){
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }

  proxy.$modal.confirm(`是否确认删除选中的数据`).then(() => {
    return delList({ids: ids})
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    queryParams.value.page = 1
    getList()
  })
}
// 批量下载
const batchDownload = () => {
  if(attachIds.length == 0){
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }
  proxy.download("/attachment/downForZip/" + attachIds.join(","), {}, '图件模板.zip');
}
// 下载
const handleDown = (attachId) => {
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId="+ encodeURIComponent(attachId)
}
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm(`是否确认删除${row.name}`).then(() => {
    return delList({ids: [row.id]})
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    queryParams.value.page = 1
    getList()
  })
}
// 多选框选中数据
let ids = reactive([])
let attachIds = reactive([])
function handleSelectionChange(selection) {
  ids = selection.map(item => item.id)
  attachIds = selection.map(item => item.attachId)
}
// 保存
const submitForm = () => {
  if(mapForm.value.id){
    let {id, name, mapDesc} = mapForm.value
    updateSave({id, name, mapDesc}).then(res => {
      if(res.code == 200){
        proxy.$modal.msgSuccess('保存成功！')
        openFile.value = false
        getList()
      }
    })
  }else{
    fileList.value = proxy.$refs["fileUpload"].fileList
    mapForm.value.attachId = fileList.value.map(item => item.attachId).join(',')
    proxy.$refs.mapRef.validate(valid => {
      if(valid){
        proxy.$modal.loading("正在发布模板，请稍候...");
        uploadSave(mapForm.value).then(res => {
          proxy.$modal.closeLoading();
          if(res.code == 200){
            proxy.$modal.alertSuccess('保存成功！')
            openFile.value = false
            getList()
          }
        }).catch(() => {
          proxy.$modal.closeLoading();
          proxy.$modal.alertError("保存失败");
        });
      }
    })
  }
}
const close = () => {
  proxy.resetForm('mapRef')
  mapForm.value.attachId = ''
  mapForm.value.id = ''
  openFile.value = false
  viewFlag.value = false
}
const beforeUpload = (file, cb) => {
  let reg = /[\u4E00-\u9FA5]/g
  if(reg.test(file.name)){
    proxy.$modal.msgError(`上传文件名称不能包含中文!`);
    cb(false)
  }
}
const uploadFile = (attachId) => {
  mapForm.value.attachId = attachId
}
// 图件类型
const getMapTypeDict = () => {
  getMapType().then(res => {
    mapTypeData.value = res.data
  })
}
const viewFlag = ref(false)
const updateUpload = (row) => {
  openFile.value = true
  viewFlag.value = true
  getView(row.id).then(res => {
    mapForm.value = res.data
  })
}

onMounted(() => {
  getMapTypeDict()
  getList()
})

</script>

<style lang="scss">
.el-dialog .el-dialog__body {
  padding: 20px 20px 0;
}
</style>